import time
from loguru import logger
from DrissionPage import Chromium
from DrissionPage.errors import ElementLostError, NoRectError, ElementNotFoundError
from read_search_file import get_complete_sheet1, get_complete_sheet_platform, get_complete_sheet_indus_people, get_complete_sheet_indus_inters, get_complete_sheet_keyword, get_complete_sheet_crowd_pack, mock_click_js
from DrissionPage.common import Keys
from create_creative import create_creative_func
import pandas as pd

'''创建单元'''
def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)
# 填充平台精选
def select_platform_vip_choose(u_view_tab, r_excel, df_platform):
    main_crowed_pack = r_excel['人群定向包']
    for p_row in df_platform.itertuples():
        sheet_pack = p_row.人群定向包
        if pd.notna(main_crowed_pack) and pd.notna(sheet_pack):
            if main_crowed_pack == sheet_pack:
                small_class = p_row.小类
                if pd.notna(small_class):
                    small_class = small_class.strip()
                    if pd.notna(p_row.一级选项):
                        one_option_arr = p_row.一级选项.strip().split('\n')
                        if '场景人群' == small_class:
                            u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=场景人群').run_js('this.click();')
                            time.sleep(1)
                            table_display = u_view_tab.ele('css:.recommend-crowdTarget .module').eles('tag:div@@class=d-table-v2').filter_one.displayed()

                            for option in one_option_arr:
                                try:
                                    option = option.strip()
                                    if option_ele := table_display.ele(f'tag:td@@class=d-table-cell-td@@style=text-align: left;@@text()={option}', timeout=2):
                                        option_ele.scroll.to_see()
                                        check_status_class_str = option_ele.prev().child().child().child().attr('class')
                                        if 'unchecked' in check_status_class_str:
                                            option_ele.prev().child().child().run_js('this.click();')
                                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                    logger.info(f"二级选项{option.strip()}没找到")
                                    continue

                        if '节促人群' == small_class:
                            u_view_tab.ele('css:.recommend-crowdTarget .module').child().ele(f'tag:div@@class$d-segment-item-muted@@text()=节促人群').click(by_js=True)
                            time.sleep(1)
                            table_display = u_view_tab.ele('css:.recommend-crowdTarget .module').eles('tag:div@@class=d-table-v2').filter_one.displayed()

                            for option in one_option_arr:
                                try:
                                    option = option.strip()
                                    if option_ele := table_display.ele(f'tag:td@@class=d-table-cell-td@@style=text-align: left;@@text()={option}', timeout=2):
                                        check_status_class_str = option_ele.prev().child().child().child().attr('class')
                                        if 'unchecked' in check_status_class_str:
                                            option_ele.prev().child().child().run_js('this.click();')
                                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                    logger.info(f"二级选项{option.strip()}没找到")
                                    continue


# 填充行业人群
def select_indus_people(u_view_tab, r_excel, df_platform):
    main_crowed_pack = r_excel['人群定向包']
    for indus_row in df_platform.itertuples():
        sheet_every_pack = indus_row.人群定向包
        if pd.notna(main_crowed_pack) and pd.notna(sheet_every_pack):
            sheet_every_pack = sheet_every_pack.strip()
            main_crowed_pack = main_crowed_pack.strip()

            if main_crowed_pack == sheet_every_pack:
                one_section = indus_row.一级选项.strip()
                if '策略人群' == indus_row.小类:
                    u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=策略人群').run_js('this.click();') # 点击策略人群
                    time.sleep(0.5)
                    table_display = u_view_tab.eles('css:.industry-crowdTarget .delight-material-cascader-panel').filter_one.displayed()
                    if not one_section == '全选':
                        table_display.child().ele('tag:div@@class=d-spinner-container').ele(f'tag:span@@text()={one_section}').parent(2).click(by_js=True)  ## 选中一级选项
                        time.sleep(0.5)
                        second_option = indus_row.二级选项
                        if pd.notna(second_option):
                            second_option = second_option.strip()
                            strategy_second_option_arr = second_option.split('\n')
                            for s in strategy_second_option_arr: ## 遍历策略人群二级选项
                                try:
                                    table_display.child(index=-1).ele('.=d-spinner-container').ele(f'tag:span@@text()={s.strip()}', timeout=5).parent(1).prev().run_js('this.click();')
                                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                    logger.info(f"二级选项{s.strip()}没找到")
                                    continue
                    else:
                        table_display.ele('css:.industry-crowdTarget .delight-material-cascader-panel .delight-material-cascader-menu:nth-child(1) .delight-material-cascader-node-all').child().click(by_js=True)  ## 全选
                if '垂类人群' == indus_row.小类:
                    u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=垂类人群').run_js('this.click();')  # 点击策略人群
                    time.sleep(0.5)
                    table_display = u_view_tab.eles('css:.industry-crowdTarget .delight-material-cascader-panel').filter_one.displayed()
                    if not one_section == '全选':
                        table_display.child().ele('tag:div@@class=d-spinner-container').ele(f'tag:span@@text()={one_section}').parent(2).click(by_js=True)  ## 选中一级选项
                        time.sleep(0.5)
                        second_option = indus_row.二级选项
                        if pd.notna(second_option):
                            second_option = second_option.strip()
                            strategy_second_option_arr = second_option.split('\n')
                            for s in strategy_second_option_arr:  ## 遍历策略人群二级选项
                                try:
                                    table_display.child(index=-1).ele('.=d-spinner-container').ele(f'tag:span@@text()={s.strip()}', timeout=5).parent(1).prev().run_js('this.click();')
                                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                    logger.info(f"二级选项{s.strip()}没找到")
                                    continue
                    else:
                        table_display.ele('css:.industry-crowdTarget .delight-material-cascader-panel .delight-material-cascader-menu:nth-child(1) .delight-material-cascader-node-all').child().click(by_js=True)  ## 全选


# 填充行业兴趣
def select_indus_inters_people(u_view_tab, r_excel, df_indus_people):
    main_crowed_pack = r_excel['人群定向包']

    for indus_row in df_indus_people.itertuples():
        sheet_every_pack = indus_row.人群定向包
        if pd.notna(main_crowed_pack) and pd.notna(sheet_every_pack):
            main_crowed_pack = main_crowed_pack.strip()
            sheet_every_pack = sheet_every_pack.strip()
            if main_crowed_pack == sheet_every_pack:
                one_section = indus_row.一级选项.strip()
                small_class = indus_row.小类
                if pd.notna(small_class):
                    small_class = small_class.strip()
                    if '行业阅读兴趣' == small_class:
                        u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=行业阅读兴趣').run_js('this.click();')  # 点击行业阅读兴趣
                        time.sleep(0.5)
                        table_display = u_view_tab.eles('css:.industryInterest_container .delight-material-cascader-panel').filter_one.displayed()

                        if not one_section == '全选':
                            try:
                                table_display.ele('tag:div@@class=d-spinner-container').ele(f'tag:span@@text()={one_section}').parent(1).prev().click(by_js=True)  ## 选中一级选项
                            except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                logger.info(f"二级选项{one_section.strip()}没找到")
                                continue
                        else:
                            table_display.ele('tag:li@@class=delight-material-cascader-node-all').child().click(by_js=True)  ## 选中一级选项
                    if '行业购物兴趣' == small_class:
                        u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=行业购物兴趣').run_js('this.click();')  # 点击行业购物兴趣
                        time.sleep(0.5)
                        table_display = u_view_tab.eles('css:.industryInterest_container .delight-material-cascader-panel').filter_one.displayed()
                        if not one_section == '全选':
                            if pd.notna(indus_row.二级选项):
                                table_display.child().ele('tag:div@@class=d-spinner-container').ele(f'tag:span@@text()={one_section}').parent(2).click(by_js=True)  ## 选中一级选项
                                time.sleep(0.5)
                                indus_inters_second_option_arr = indus_row.二级选项.split('\n')  ## 行业购物兴趣二级兴趣
                                for s in indus_inters_second_option_arr:  ## 遍历行业购物兴趣二级选项
                                    try:
                                        table_display.child(index=-1).ele('.=d-spinner-container').ele(f'tag:span@@text()={s.strip()}', timeout=5).parent(1).prev().run_js('this.click();')
                                    except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                        logger.info(f"二级选项{s.strip()}没找到")
                                        continue
                            else:
                                table_display.child().ele('tag:div@@class=d-spinner-container').ele(f'tag:span@@text()={one_section}').parent(2).child().click(by_js=True)  ## 一级选项全选
def select_keyword_people(u_view_tab, r_excel, df_keyword):
    main_crowed_pack = r_excel['人群定向包']
    if pd.notna(main_crowed_pack):
        main_crowed_pack = main_crowed_pack.strip()
        for word_row in df_keyword.itertuples():
            sheet_every_pack = word_row.人群定向包
            if pd.notna(sheet_every_pack):
                sheet_every_pack = sheet_every_pack.strip()
                if main_crowed_pack == sheet_every_pack:
                    small_type = word_row.小类
                    if pd.notna(small_type):
                        small_type = small_type.strip()
                        keyword_option_arr = word_row.关键词.strip().split('\n')  ## 关键词列表
                        if '关键词兴趣' == small_type:
                            u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=关键词兴趣').run_js('this.click();')  # 点击关键词兴趣
                            table_display = u_view_tab.ele('css:.keyword-target-container')
                            for k in keyword_option_arr:
                                try:
                                    table_display.ele('tag:div@@class=keywords-interest').ele('tag:input@@class=d-text@@type=text@@placeholder=请输入关键词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', k.strip()) # 输入关键词兴趣查询框
                                    # u_view_tab.input(Keys.ENTER)
                                    table_display.ele('.=keywords-interest').ele('tag:div@@class=search-icon').child().run_js('this.click();') # 点击关键词兴趣搜索按钮
                                    time.sleep(0.8)
                                    if keyword_move_ele := table_display.ele(f'tag:div@@class=keywords-interest-container').ele('tag:div@@class=d-table__content').ele(f'tag:td@@class=d-table-cell-td@@text()={k.strip()}', timeout=2):
                                        class_str = keyword_move_ele.prev().child().child().child().attr('class')
                                        if 'unchecked' in class_str:
                                            keyword_move_ele.prev().child().child().run_js('this.click();')  # 选择关键词兴趣
                                            u_view_tab.wait(0.1)
                                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                                    print(e)
                                    continue

                        if '行为' in small_type:
                            u_view_tab.ele(f'tag:div@@class$d-segment-item-muted@@text()=关键词行为').run_js('this.click();')  # 点击关键词行为
                            time.sleep(1)
                            table_display = u_view_tab.ele('css:.keyword-target-container')
                            if ':' in small_type:  # 如果存在条件搜索
                                time_and_range = small_type.split(':')[1]
                                time_sel = time_and_range.split('-')[0]
                                content_range = time_and_range.split('-')[1]
                                u_view_tab.ele(f'tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text()={time_sel.strip()}').run_js('this.click();')  # 选中时间下拉框
                                for r in content_range.split(';'):
                                    if r == '搜索':
                                        s_class_str = u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph@@text()=搜索 ').parent(2).prev().child().child().child().attr('class')
                                        if 'unchecked' in s_class_str:
                                            u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph@@text()=搜索 ').run_js('this.click();')  # 选中搜索
                                    if r == '互动':
                                        h_class_str = u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph@@text()=互动 ').parent(2).prev().child().child().child().attr('class')
                                        if 'unchecked' in h_class_str:
                                            u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph@@text()=互动 ').run_js('this.click();')  # 选中互动
                                    if r == '阅读':
                                        y_class_str = u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph@@text()=阅读 ').parent(2).prev().child().child().child().attr('class')
                                        if 'unchecked' in y_class_str:
                                            u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph@@text()=阅读 ').run_js('this.click();')  # 选中阅读

                            # 否则直接输入关键词
                            for k in keyword_option_arr:
                                try:
                                    table_display.ele('tag:div@@class=keywords-behavior').ele('.=search').ele('tag:input@@class=d-text@@type=text@@placeholder=请输入关键词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', k.strip()) # 输入关键词兴趣查询框
                                    # u_view_tab.input(Keys.ENTER)
                                    table_display.ele('.=keywords-behavior').ele('tag:div@@class=search-icon').child().run_js('this.click();')  # 点击关键词兴趣搜索按钮
                                    time.sleep(0.8)
                                    if keyword_move_ele := table_display.ele(f'tag:div@@class=keywords-behavior-container').ele('tag:div@@class=d-table__content').ele(f'tag:td@@class=d-table-cell-td@@text()={k.strip()}', timeout=2):
                                        class_str = keyword_move_ele.prev().child().child().child().attr('class')
                                        if 'unchecked' in class_str:
                                            keyword_move_ele.prev().child().child().run_js('this.click();')  # 选择关键词行为
                                            u_view_tab.wait(0.1)
                                except (ElementLostError, NoRectError, AttributeError) as e:  # AttributeError
                                    print(e)
                                    continue
def select_df_crowd_pack(u_view_tab, r_excel, df_crowd_pack):
    main_crowed_pack = r_excel['人群定向包']
    if pd.notna(main_crowed_pack):
        main_crowed_pack = main_crowed_pack.strip()

        for crowd_row in df_crowd_pack.itertuples():
            sheet_every_pack = crowd_row.人群定向包
            if pd.notna(sheet_every_pack):
                sheet_every_pack = sheet_every_pack.strip()
                if main_crowed_pack == sheet_every_pack:
                    pack_names = crowd_row.包名
                    pack_name_arr = pack_names.strip().split('\n')  ## 关键词列表
                    pack_name_arr = list(set(pack_name_arr))  ## 去重
                    table_display = u_view_tab.ele('css:.common-crowdTarget')
                    for p in pack_name_arr:
                        table_display.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', p.strip())
                        u_view_tab.wait(0.3)
                        if pack_input := table_display.ele('.=crowdTarget_cascader').ele(f'tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph d-text-nowrap d-text-ellipsis@@text()^{p.strip()}', timeout=3):
                            class_str_crowed_pack_class_str = pack_input.parent(1).prev().child().child().child().attr('class')
                            if 'unchecked' in class_str_crowed_pack_class_str:
                                pack_input.parent(1).prev().child().child().run_js('this.click();')  # 选择人群包
                            else:
                                continue
                        else:
                            continue

'''选择高级定向'''
def select_senior_target(u_view_tab, r_excel, file_path, log_callback, df_sheet):
    plan_crowd_pack = r_excel['人群定向包']
    plan_name = r_excel['计划名']

    combine_pack_arr = []
    # 选中平台精选
    df_platform = get_complete_sheet_platform(file_path)
    if not df_platform.empty:
        platform_crowd_pack_arr = df_platform['人群定向包'].tolist()
        combine_pack_arr.extend(platform_crowd_pack_arr)

        if plan_crowd_pack in platform_crowd_pack_arr:
            if platform_choose_ele := u_view_tab.ele('tag:span@@class$d-tabs-header-label d-text-nowrap@@text()=平台精选', timeout=5):
                platform_choose_ele.run_js('this.click();') # 点击平台精选
                time.sleep(1)
                select_platform_vip_choose(u_view_tab, r_excel, df_platform)

    # 选中行业人群
    df_indus_people = get_complete_sheet_indus_people(file_path)
    if not df_indus_people.empty:
        df_indus_people_arr = df_indus_people['人群定向包'].tolist()
        combine_pack_arr.extend(df_indus_people_arr)

        if plan_crowd_pack in df_indus_people_arr:
            if indus_crowd_ele := u_view_tab.ele('tag:span@@class$d-tabs-header-label d-text-nowrap@@text()=行业人群', timeout=5):
                indus_crowd_ele.click(by_js=True)  # 点击行业人群
                time.sleep(1)
                select_indus_people(u_view_tab, r_excel, df_indus_people)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【行业人群】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中行业兴趣
    df_indus_inters_people = get_complete_sheet_indus_inters(file_path)
    if not df_indus_inters_people.empty:
        df_indus_inters_arr = df_indus_inters_people['人群定向包'].tolist()
        combine_pack_arr.extend(df_indus_inters_arr)

        if plan_crowd_pack in df_indus_inters_arr:
            if indus_interest_ele := u_view_tab.ele('tag:span@@class$d-tabs-header-label d-text-nowrap@@text()=行业兴趣', timeout=5):
                indus_interest_ele.click(by_js=True)  # 点击行业兴趣
                time.sleep(1)
                select_indus_inters_people(u_view_tab, r_excel, df_indus_inters_people)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【行业兴趣】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中关键词
    df_keyword = get_complete_sheet_keyword(file_path)
    if not df_keyword.empty:
        df_keyword_arr = df_keyword['人群定向包'].tolist()
        combine_pack_arr.extend(df_keyword_arr)

        if plan_crowd_pack in df_keyword_arr:
            if indus_interest_ele := u_view_tab.ele('tag:span@@class$d-tabs-header-label d-text-nowrap@@text()=关键词', timeout=5):
                indus_interest_ele.click(by_js=True)  # 点击关键词
                time.sleep(1)
                select_keyword_people(u_view_tab, r_excel, df_keyword)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【关键词】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中人群包
    df_crowd_pack = get_complete_sheet_crowd_pack(file_path)
    if not df_crowd_pack.empty:
        df_crowd_pack_arr = df_crowd_pack['人群定向包'].tolist()
        combine_pack_arr.extend(df_crowd_pack_arr)

        if plan_crowd_pack in df_crowd_pack_arr:
            if crowd_pack_ele := u_view_tab.ele('tag:span@@class$d-tabs-header-label d-text-nowrap@@text()=人群包', timeout=5):
                crowd_pack_ele.click(by_js=True)  # 点击人群包
                time.sleep(1)
                select_df_crowd_pack(u_view_tab, r_excel, df_crowd_pack)
    # 智能扩量
    intelligent_expansion_handle(df_sheet, r_excel, u_view_tab)

    # 关闭高级定向框
    if confirm_add_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 确定添加 ', timeout=2):
        if confirm_add_ele.parent(2).states.is_clickable:
            confirm_add_ele.parent(2).click(by_js=True)  # 点击确定添加按钮
        else:
            logger.info(f"高级定向列表无法添加人群包，请检查对应标签页查看具体原因")
            log_message(log_callback, f"高级定向列表无法添加人群包，请检查对应标签页查看具体原因", "red")
            return
        time.sleep(2)

    if plan_crowd_pack not in combine_pack_arr:
        logger.info(f"所有子选项卡中的人群定向包列选项:{combine_pack_arr}")
        log_message(log_callback, f"当前计划人群定向包列:【{plan_crowd_pack}】在子选项卡中不存在, 检查主表计划名:【{plan_name}】 - 人群定向包列填写是否正确", "red")
        return


'''选择更多定向'''
def select_more_target(u_view_tab, r_excel, log_callback):
    gender = r_excel['性别']
    area = r_excel['地域']
    age = r_excel['年龄']
    platform = r_excel['平台']
    tel_price = r_excel['手机价格']

    if more_target_ele := u_view_tab.ele('tag:div@@class=show-more-title@@text()=更多定向', timeout=2):
        more_target_ele.click(by_js=True)

    # 性别
    if gender != '不限' and gender != '全选':
        u_view_tab.ele('tag:span@@class=form-item-label-text@@text()=性别', timeout=2).scroll.to_center()  # 滚到性别位置
        if u_view_tab.ele(f'tag:div@@class=flexible align-center@@text()={gender.strip()}', timeout=2):
            u_view_tab.ele(f'tag:div@@class=flexible align-center@@text()={gender.strip()}').parent(3).click(by_js=True)  ## 点击男或女

    # 地域
    func_area_handle(area, u_view_tab)
    # 年龄
    if  '不限' != age and age != '全选':
        u_view_tab.ele('#=unit.targetAge').scroll.to_center()
        if pd.notna(age):
            age_arr = age.strip().split('\n')
            for a in age_arr:
                try:
                    a = a.strip()
                    if age_ele := u_view_tab.ele('#=unit.targetAge').ele(f'tag:span@@class=checkbox-label@@text()={a}', timeout=2):
                        age_class_str = age_ele.parent(1).prev().prev().attr('class')
                        if 'unchecked' in age_class_str:
                            age_ele.parent(2).click(by_js=True)  ## 选中年龄段
                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                    logger.info(f"年龄:{a.strip()}没找到")
                    log_message(log_callback, f"年龄:{a.strip()}没找到, 跳过当前选项继续", "red")
                    continue



    # 平台安卓或者ios
    if target_ele := u_view_tab.ele('#=unit.targetDevice'):
        target_ele.scroll.to_center()
        if '不限' != platform and '全选' != platform:
            if pd.notna(platform):
                try:
                    if device_ele := target_ele.ele(f'tag:input@@type=checkbox@@value={platform}', timeout=2):
                        device_class_str = device_ele.prev().attr('class')
                        if 'unchecked' in device_class_str:
                            device_ele.parent(1).click(by_js=True)  ## 选中年龄段
                except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                    logger.info(f"平台选项:{platform.strip()}没找到, 跳过当前选项继续执行", "red")
                    log_message(log_callback, f"平台选项:{platform.strip()}没找到, 跳过当前选项继续执行", "red")


    # 手机价格
    if price_ele := u_view_tab.ele('#=unit.targetDevicePrice'):
        price_ele.scroll.to_center()

        if tel_price != '不限' and tel_price != '全选':
            if pd.notna(tel_price):
                tel_price_arr = tel_price.strip().split('\n')
                for tel in tel_price_arr:
                    try:
                        if u_view_tab.ele(f'tag:span@@text()={tel.strip()}', timeout=1):
                            price_class_str = u_view_tab.ele(f'tag:span@@class=checkbox-label@@text()={tel.strip()}').parent(1).prev().prev().attr('class')
                            if 'unchecked' in price_class_str:
                                u_view_tab.ele(f'tag:span@@class=checkbox-label@@text()={tel.strip()}').parent(2).click(by_js=True)  ## 选中各手机段
                    except (ElementLostError, NoRectError, AttributeError, ElementNotFoundError) as e:
                        logger.info(f"手机价格{tel.strip()}没找到")
                        log_message(log_callback, f"手机价格{tel.strip()}没找到, 跳过当前选项继续", "red")
                        continue




def func_area_handle(area, u_view_tab):
    if '中国' in area:
        if area_ele := u_view_tab.ele('#=unit.targetAreaCode').ele(f'tag:div@@class=flexible align-center@@text()=自定义', timeout=1.5):
            area_ele.scroll.to_center()
            area_ele.parent(3).click(by_js=True)
            time.sleep(1.5)

            if area_all_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-checkbox-label@@text()= 全选 ', timeout=2):
                all_class_str = area_all_ele.prev().prev().attr('class')
                if 'unchecked' not in all_class_str:  # 如果已经选了全选， 先取消
                    area_all_ele.parent(1).click(by_js=True)
                    time.sleep(0.5)

            if china_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-checkbox-label@@text()=中国', timeout=2):
                china_class_str = china_ele.prev().prev().attr('class')
                if 'unchecked' in china_class_str:
                    china_ele.parent(1).click(by_js=True)
                    time.sleep(0.5)
                else:
                    area_all_ele.parent(1).click(by_js=True)
                    china_ele.parent(1).click(by_js=True)

                if any(sep in area for sep in [':not', '：not']):
                    cities = area.split(':not')[1].strip()
                    excludes_cities = cities.split('-')
                    for city in excludes_cities:
                        city = city.strip()
                        if city_ele := u_view_tab.ele(f'tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-checkbox-label@@text()={city}', timeout=2):
                            city_ele.scroll.to_center()
                            city_ele.parent(1).click(by_js=True)
        else:
            if any(sep in area for sep in [':not', '：not']):
                if single_area_ele := u_view_tab.ele('tag:span@@class=form-item-label-text@@text()=地域', timeout=1):
                    single_area_ele.parent(1).next().child().child().click(by_js=True)
                    time.sleep(1.5)

                cities = area.split(':not')[1].strip()
                excludes_cities = cities.split('-')
                for city in excludes_cities:
                    city = city.strip()
                    if city_ele := u_view_tab.ele(f'tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-checkbox-label@@text()={city}', timeout=2):
                        city_ele.scroll.to_center()
                        city_ele.parent(1).click(by_js=True)


        if confirm_add_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 确定添加 ', timeout=2):
            if confirm_add_ele.parent(2).states.is_clickable:
                confirm_add_ele.parent(2).click(by_js=True)  # 点击确定添加按钮

'''创建单元主流程'''


def handle_search_recom(r_excel, u_view_tab, df_sheet, log_callback):
    if '关键词' in df_sheet.columns:
        keywords = r_excel['关键词']

        # 点击添加关键词
        u_view_tab.ele('tag:div@@class=keywords-card-empty-text@@text()= 添加关键词 ').scroll.to_center()
        u_view_tab.ele('tag:div@@class=keywords-card-empty-text@@text()= 添加关键词 ').parent(1).click(by_js=True)

        time.sleep(1)

        keyword_arr = keywords.strip().split('\n')
        u_view_tab.ele('tag:input@@placeholder=请输入新的关键词进行添加，多关键词可使用折行或；间隔').run_js('this.focus();')
        for k in keyword_arr:
            u_view_tab.actions.input(k).input(Keys.ENTER)
            time.sleep(0.1)

        u_view_tab.ele('css:.keywords-edit-drawer-content-box-right div.d-table-affix-header-ele > table > thead > tr > th:nth-child(1) > div > div > div').click(by_js=True) # 全选关键词
        time.sleep(0.1)

        ## 修改匹配方式
        if '关键词匹配方式' in df_sheet.columns:
            match_type = r_excel['关键词匹配方式']
            if pd.notna(match_type):
                u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 修改匹配方式 ').parent(2).click(by_js=True)
                time.sleep(0.5)
                u_view_tab.ele(f'tag:span@@text()={match_type.strip()}').parent(1).click(by_js=True)
                u_view_tab.ele('tag:button@@class=d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white@@text()=确定').click(by_js=True)
                time.sleep(0.2)

            # 精准包含
            if match_type == '精准匹配':
                if '精准包含' in df_sheet.columns:
                    accurate_inclusion = r_excel['精准包含']

                    if accurate_inclusion == '关闭':
                        if contain_clickable_ele := u_view_tab.ele('tag:div@@class=keywords-edit-drawer-content-box-right-header-title-switch-text@@text()= 精准包含 ', timeout=2).parent(1).prev():
                            is_checked_condition_class = contain_clickable_ele.child().child().child().attr('class')
                            if 'unchecked' not in is_checked_condition_class:
                                contain_clickable_ele.click(by_js=True)
                    else:
                        if contain_clickable_ele := u_view_tab.ele('tag:div@@class=keywords-edit-drawer-content-box-right-header-title-switch-text@@text()= 精准包含 ', timeout=2).parent(1).prev():
                            is_checked_condition_class = contain_clickable_ele.child().child().child().attr('class')
                            if 'unchecked' in is_checked_condition_class:
                                contain_clickable_ele.click(by_js=True)

        # 关键词出价
        if '关键词出价' in df_sheet.columns:
            bid_price = r_excel['关键词出价']
            if pd.notna(bid_price):
                u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 修改关键词出价 ').parent(2).click(by_js=True)
                time.sleep(0.5)
                u_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入价格@@min=0.3@@max=4999').input(bid_price, clear=True)
                u_view_tab.ele('tag:button@@class=d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white@@text()=确定').click(by_js=True)
                time.sleep(0.2)

        # 确定添加
        u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 确定添加 ').parent(2).click(by_js=True)
        time.sleep(0.8)

    ## 智能拓词关闭
    if '智能拓词' in df_sheet.columns:
        words_status = r_excel['智能拓词']
        if words_ele := u_view_tab.ele('tag:div@@text()= 智能拓词 ', timeout=1.5):
            words_ele.scroll.to_center()
            words_ele_class_status = words_ele.next().child().child().child().attr('class')
            if '关闭' == words_status:
                if 'unchecked' not in words_ele_class_status:
                    words_ele.next().click(by_js=True)
            else:
                if 'unchecked' in words_ele_class_status:
                    words_ele.next().click(by_js=True)

    # 点击更多定向
    if more_target_ele := u_view_tab.ele('tag:div@@class=show-more-title@@text()=更多定向', timeout=1.5):
        more_target_ele.run_js('this.click();')
        time.sleep(0.2)

    # 地域
    if '地域' in df_sheet.columns:
        area = r_excel['地域']
        func_area_handle(area, u_view_tab)
        ## 年龄
        # if '不限' != age and age != '全选':
        #     if age_option_exists := u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(5) > div:nth-child(1) > div > span:nth-of-type(2)', timeout=2):
        #         if age_option_exists.states.is_displayed:
        #             if pd.notna(age):
        #                 age_option_exists.click(by_js=True)  ## 取消年龄不限
        #                 age_arr = age.split('\n')
        #                 for a in age_arr:
        #                     if age_option := u_view_tab.ele(f'tag:span@@text()={a.strip()}', timeout=2):
        #                         age_option.parent(1).click(by_js=True)  ## 选中各年龄段
        #                     else:
        #                         break


def create_unit(u_view_tab, r_excel, browser, file_path, df_sheet=None, log_callback=None):
    unit_name = r_excel['单元名称']
    note_id = r_excel['笔记ID']
    launch_loc = r_excel['投放位置']

    # 单元名称
    u_view_tab.ele('tag:h5@@text()= 单元 ').next().ele('tag:input@@class=d-text@@maxlength=50').input(unit_name[:49], clear=True)
    log_message(log_callback, f"正在自动填充单元名称:{unit_name}", "purple")

    # 批量添加笔记
    # if u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 批量添加 ', timeout=2):
    #     batch_add_note_ids(note_id, u_view_tab, log_callback)
    # else:

    # 信息流推广 - 人群定向包
    if launch_loc == '信息流推广':
        crowd_pack_handle(file_path, log_callback, r_excel, u_view_tab, unit_name, df_sheet)
    if launch_loc == '搜索推广':
        handle_search_recom(r_excel, u_view_tab, df_sheet, log_callback)

    # 排除特定人群
    # exclude_target_crowed(df_sheet, r_excel, u_view_tab)

    # 定向拓展
    # target_expansion_handle(df_sheet, r_excel, u_view_tab)

    # 目标成本
    if '目标成本' in df_sheet.columns:
        if bid_card_ele := u_view_tab.ele('#=unit.bidCard', timeout=1):
            target_cost = r_excel['目标成本']
            if pd.notna(target_cost):
                bid_card_ele.ele('tag:input@@class=d-text@@placeholder=请输入').input(target_cost, clear=True)  # 目标成本
                log_message(log_callback, f"正在自动填充目标成本:{target_cost}", "purple")

    # 搜索出价系数
    # if search_discount_rate_ele := u_view_tab.ele('tag:span@@text()=搜索出价系数', timeout=1):
    #     search_discount_rate_ele.scroll.to_center()
    #     search_discount_rate = r_excel['搜索出价系数']
    #     if pd.notna(search_discount_rate):
    #         search_discount_rate_ele.parent(1).next().ele('tag:input@@class=d-text@@placeholder=请输入，溢价范围 1-10').input(search_discount_rate, clear=True)  # 目标成本

    # if u_view_tab.ele('@text():单元名称已存在', timeout=1):
    #     log_message(log_callback, f"单元名称:{unit_name} - 已存在", "red")
    #     return

    # 选择笔记
    log_message(log_callback, f"正在自动搜索笔记:{note_id}", "purple")
    note_dict = single_add_note_id(log_callback, note_id, u_view_tab)  # 单条添加笔记

    # 创意信息
    create_creative_func(u_view_tab, r_excel, browser, file_path, log_callback, df_sheet, note_dict)

def target_expansion_handle(df_sheet, r_excel, u_view_tab):
    if '定向拓展' in df_sheet.columns:
        if target_expand_ele := u_view_tab.ele('tag:span@@text()=定向拓展', timeout=1):
            target_expand_ele.scroll.to_center()
            target_expand = r_excel['定向拓展']

            target_expand_ele_str = target_expand_ele.parent(1).next().ele('.d-switch-top').child().attr('class')
            if target_expand == '开':
                if 'unchecked' in target_expand_ele_str:
                    target_expand_ele.parent(1).next().child().child().run_js('this.click();')
            else:
                if 'unchecked' not in target_expand_ele_str:
                    target_expand_ele.parent(1).next().child().child().run_js('this.click();')


def intelligent_expansion_handle(df_sheet, r_excel, u_view_tab):
    if '智能扩量' in df_sheet.columns:
        if intelligent_expansion_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=启用智能扩量', timeout=2):
            intelligence_expand = r_excel['智能扩量']
            expand_class_str = intelligent_expansion_ele.parent(1).prev().prev().attr('class')
            if intelligence_expand == '开':
                if 'unchecked' in expand_class_str:
                    intelligent_expansion_ele.parent(2).run_js('this.click();')
            else:
                if 'unchecked' not in expand_class_str:
                    intelligent_expansion_ele.parent(2).run_js('this.click();')


def exclude_target_crowed(df_sheet, r_excel, u_view_tab):
    if '排除特定人群' in df_sheet.columns:
        if exclude_people_ele := u_view_tab.ele('tag:span@@text()=排除特定人群', timeout=2):
            exclude_people_ele.scroll.to_center()
            exclude_people = r_excel['排除特定人群']
            if pd.notna(exclude_people):
                if exclude_people != '不排除':
                    exclude_people_arr = exclude_people.split('-')
                    trans_user_ele = u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph@@text()=已转化用户', timeout=1)
                    trans_user_ele.scroll.to_center()
                    if trans_user_ele:
                        crowed_pack_class_str = trans_user_ele.parent(1).prev().prev().attr('class')
                        if 'unchecked' in crowed_pack_class_str:
                            trans_user_ele.parent(2).click(by_js=True)  ## 点击已转化用户
                            time.sleep(0.2)
                            for p in exclude_people_arr:
                                p = p.strip()
                                if items_ele := u_view_tab.ele(f'tag:div@@class=flexible align-center@@text()={p}'):
                                    items_ele.scroll.to_center()
                                    items_ele.parent(3).click(by_js=True)  ## 选中各人群包


def crowd_pack_handle(file_path, log_callback, r_excel, u_view_tab, unit_name, df_sheet):
    if '关联定向包' in df_sheet.columns:
        relative_pack = r_excel['关联定向包']
        if pd.isna(relative_pack):

            crowd_pack = r_excel['人群定向包']
            if crowd_pack != '智能定向':
                if radio_senior_target_ele := u_view_tab.ele('tag:div@@class=flexible align-center@@text()=高级定向', timeout=2):
                    radio_senior_target_ele.scroll.to_center()
                    radio_senior_target_ele.parent(3).click(by_js=True)  # 点击高级定向
                    time.sleep(1)
                    select_senior_target(u_view_tab, r_excel, file_path, log_callback, df_sheet)
                    select_more_target(u_view_tab, r_excel, log_callback)
            else:
                if intelligent_target_ele := u_view_tab.ele('tag:div@@class=flexible align-center@@text()=智能定向', timeout=2):
                    intelligent_target_ele.scroll.to_center()
                    intelligent_target_ele.parent(3).click(by_js=True)  # 点击高级定向
                    time.sleep(1.5)
                    select_more_target(u_view_tab, r_excel, log_callback)

        else:  # 关联包不等于空的时候优先填写关联定向包
            relative_pack = r_excel['关联定向包'].strip()
            choose_relative_pack(relative_pack, u_view_tab, unit_name, log_callback)

def single_add_note_id(log_callback, note_id, u_view_tab):
    if pd.notna(note_id):
        if add_note_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=添加笔记', timeout=2):
            add_note_ele.scroll.to_center()
            add_note_ele.parent(1).click(by_js=True)  # 点击添加笔记按钮
        note_id_arr = str(note_id).strip().split('\n')
        note_dict = {}
        for i, note in enumerate(note_id_arr):
            note = note.strip()
            select_note_and_choose(note, u_view_tab, log_callback, note_dict)

        if add_button_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 确认添加 ', timeout=2):
            add_button_ele.parent(2).click(by_js=True)  # 确认添加按钮
        return note_dict
def batch_add_note_ids(note_id, u_view_tab, log_callback):
    note_id_arr = click_batch_add_note_id_and_add_note_id(note_id, u_view_tab)

    # 二次校验笔记ID是否正确
    for i, note in enumerate(note_id_arr):
        while True:
            try:
                u_view_tab.ele('tag:div@@text()=笔记id').wait.displayed()
                if u_view_tab.ele('tag:div@@text()=笔记id', timeout=5):
                    note_id_id = u_view_tab.ele('tag:div@@text()=笔记id').parent(3).next().child(index=i + 1).child(index=2).text
                    if note_id_id == note:
                        break
                    log_message(log_callback, f'选中的笔记ID有误, 重新选择笔记ID: {i + 1} 次', "red")
                    u_view_tab.ele('tag:div@@text()=笔记id').parent(3).next().child(index=i + 1).ele('tag:td@@class=d-table__cell--fixed-right d-table-cell-td').child().run_js('this.click();')  # 删掉这条笔记重新选
                    new_note = click_batch_add_note_id_and_add_note_id(note, u_view_tab)



            except ElementNotFoundError as e:
                print(f'笔记ID搜索为空:{note_id}, 检查笔记ID')
                log_message(log_callback, f'笔记ID - {note_id}-搜索为空:, 检查笔记ID', "red")
                break


def click_batch_add_note_id_and_add_note_id(note_id, u_view_tab):
    u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 批量添加 ').parent(2).click(by_js=True)
    time.sleep(1)
    footer_container = u_view_tab.ele('tag:div@@class=d-modal-footer')
    note_id_arr = note_id.strip().split('\n')
    u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=回车输入多个 ID，最多 100 条').run_js('this.focus();')
    for note in note_id_arr:
        u_view_tab.actions.input(note).input(Keys.ENTER)
        time.sleep(0.2)
    u_view_tab.ele('tag:a@@class$--size-text-paragraph btn-validate@@text()=搜索').click(by_js=True)
    time.sleep(1)
    footer_container.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认添加', timeout=2).parent(2).wait.enabled()
    footer_container.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认添加', timeout=2).parent(2).click(by_js=True)
    # u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=取消', timeout=2).parent(2).click()
    u_view_tab.wait(1.5)
    return note_id_arr


def choose_relative_pack(relative_pack, u_view_tab, unit_name, log_callback):
    u_view_tab.ele('tag:a@@class=d-text d-link --color-primary --size-text-paragraph@@text()= 关联定向包 ').click(by_js=True)  # 关联定向包
    u_view_tab.wait(1)
    if relative_pack_str := u_view_tab.ele(f'tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text()={relative_pack}', timeout=2):
        relative_pack_str.parent(4).run_js(mock_click_js)
        time.sleep(0.5)
        u_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认关联').parent(2).click(by_js=True)  # 确认关联

        if u_view_tab.ele('@text():我知道了', timeout=1):
            u_view_tab.ele('@text():我知道了').parent(2).click(by_js=True)  # 我知道了
        u_view_tab.wait(2.5)
    else:
        log_message(log_callback, f"关联定向包:[{relative_pack}]不存在, 请检查单元名:{unit_name}的关联定向包列", "red")
        return


def select_note_and_choose(note_id, u_view_tab, log_callback, note_dict):
    if note_input_ele := u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID或笔记描述', timeout=2):
        note_input_ele.run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', note_id)
        note_input_ele.input(Keys.ENTER)
        time.sleep(2)

    main_table_ele = u_view_tab.ele('tag:tbody@@class=d-table__body')
    if choose_note_ele := main_table_ele.ele(f'tag:span@@class=d-text --color-static --color-text-paragraph --size-text-small d-text-nowrap d-text-ellipsis@@text()${note_id}', timeout=2):
        note_choose_class_str = choose_note_ele.parent(4).prev().child().child().child().attr('class')
        if 'unchecked' in note_choose_class_str:
            checkbox_class_str = choose_note_ele.parent(4).prev().child().child().attr('class')
            if 'disabled' not in checkbox_class_str:
                choose_note_ele.parent(4).prev().child().child().click(by_js=True)  ## 选择笔记
                time.sleep(0.3)
                note_dict[choose_note_ele.parent(1).prev().child().text] = note_id
            else:
                log_message(log_callback, f"笔记ID:[{note_id}]被禁用无法选中", "red")
                logger.info(f"笔记ID:[{note_id}]被禁用无法选中")
    else:
        log_message(log_callback, f"笔记ID:【{note_id}】查询为空", "red")
        logger.info(f"笔记ID:【{note_id}】查询为空")


def handle_operate_too_fast(unit_next_button_ele, unit_view_tab, unit_name, log_callback):
    max_retries = 10  # 最大重试次数
    retry_count = 0

    while retry_count < max_retries:
        # 先检查是否已经进入下一页
        # if unit_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=2):
        #     break
        unit_next_button_ele.click(by_js=True)

        # 弹窗阻塞
        ## d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white
        if alert_remind_range_small_ele := unit_view_tab.ele('tag:span@@text()=继续', timeout=0.5):
            logger.info(f"创建单元界面遇到弹窗阻塞")
            log_message(log_callback, f"单元名称:{unit_name}在创建单元界面遇到弹窗阻塞", "red")
            alert_remind_range_small_ele.parent(2).click(by_js=True)

        if unit_view_tab.ele('@text():操作频繁', timeout=1.5):
            log_message(log_callback, f"创建单元页面创建单元:{unit_name} - 触发操作频繁,正在重试({retry_count + 1}/{max_retries})", "red")
            logger.info(f"操作频繁，等待后重试 ({retry_count + 1}/{max_retries})")
            time.sleep(2 * (retry_count + 1))
            # try:
            #     unit_next_button_ele.click()
            # except NoRectError:
            #     log_message(log_callback, f"单元页面没找到下一步按钮:{unit_name} - 页面已跳转，停止重试", "green")
            #     break
            retry_count += 1
        else:
            break  # 没有"操作频繁"提示时退出循环

    if retry_count == max_retries:
        log_message(log_callback, f"单元名称:{unit_name} - 已达到最大重试次数，仍然操作频繁", "red")
        logger.error("已达到最大重试次数，仍然操作频繁")
    else:
        log_message(log_callback, f"单元名称: {unit_name}-在重试({retry_count + 1}/{max_retries})次后成功执行下一步", "green")
        logger.info("操作成功执行")


# if __name__ == '__main__':
#     # file_path = r"../shared/种草-信息视频流--创建计划-样例.xlsx"
#     file_path = r"D:\Users\Desktop\星伴-6.11-3.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/unit/123252935/4/1?isStep=true&AFormGrayFlag=false&vSellerId=683447d197bb7c00152b2c95')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_unit(unit_view_tab, row, browser, file_path, df_sheet=sheet1_data)



